package cn.easier.activity.console.controller;

import cn.easier.activity.console.entity.ActivityRoleUser;
import cn.easier.activity.console.entity.LogCountParams;
import cn.easier.activity.console.entity.SignMessageParams;
import cn.easier.activity.console.repository.ActivityRoleUserRepository;
import cn.easier.activity.console.service.DataStatisticsService;
import cn.easier.activity.console.utils.ExcelUtil;
import cn.easier.activity.console.vo.Datas;
import cn.easier.activity.web.dto.ActivityRecordDto;
import cn.easier.activity.web.entity.ActivityInfo;
import cn.easier.activity.web.entity.ActivityRecord;
import cn.easier.club.base.dto.ResultInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 数据统计相关
 *
 * @author lixiaopeng
 */
@RestController
@RequestMapping("/data-statists")
public class DataStatisticsController extends BaseController {

    private Logger log = LoggerFactory.getLogger(DataStatisticsController.class);

    @Resource
    private DataStatisticsService dataStatisticsService;

    private final ActivityRoleUserRepository activityRoleUserRepository;

    public DataStatisticsController(ActivityRoleUserRepository activityRoleUserRepository) {
        this.activityRoleUserRepository = activityRoleUserRepository;
    }

    /**
     * 获取所有的活动信息
     */
    @GetMapping("/get-activitys")
    public List<ActivityInfo> getAllActivity() {
        String user = getPrincipal().getUsername();
        String authoritiesStr = getPrincipal().getAuthoritiesStr();
        List<ActivityInfo> list;
        if (authoritiesStr.equals("ROLE_USER_SELF")) {
            list = dataStatisticsService.getAllActivityByUser(user);
        } else {
            list = dataStatisticsService.getAllActivity();
        }
        return list;
    }

    @GetMapping("/find-all-by-conditions")
    public ResultInfo findAllByConditions(@RequestParam(value = "activityId", required = false) Integer activityId,
                                          @RequestParam(value = "phoneNum", required = false) String phoneNum,
                                          @RequestParam(value = "recordNo", required = false) String recordNo,
                                          @RequestParam(value = "prizeType", required = false) Integer prizeType,
                                          @RequestParam(value = "begin", defaultValue = "0") int begin,
                                          @RequestParam(value = "count", defaultValue = "10") int count) {
        String user = getPrincipal().getUsername();
        String authoritiesStr = getPrincipal().getAuthoritiesStr();
        if (!authoritiesStr.equals("ROLE_USER_SELF")) {
            user = null;
        }
        return dataStatisticsService.findAllByConditionsAndUser(user, activityId, phoneNum, recordNo, prizeType, begin, count);
    }

    @GetMapping("/export-by-conditions")
    public void exportByConditions(@RequestParam(value = "activityId", required = false) Integer activityId,
                                   @RequestParam(value = "phoneNum", required = false) String phoneNum,
                                   @RequestParam(value = "recordNo", required = false) String recordNo,
                                   @RequestParam(value = "prizeType", required = false) Integer prizeType, HttpServletResponse response) {
        String fileName = "中奖记录";
        try {
            String user = getPrincipal().getUsername();
            String authoritiesStr = getPrincipal().getAuthoritiesStr();
            List<ActivityRecordDto> list;
            if (authoritiesStr.equals("ROLE_USER_SELF")) {
                list = dataStatisticsService.exportByConditionsAndUser(activityId, phoneNum, user, recordNo, prizeType);
            } else {
                list = dataStatisticsService.exportByConditions(activityId, phoneNum, recordNo, prizeType);
            }
            log.info("导出中奖记录条数=>{}", list.size());
            List<Map<String, String>> PROPERTIES = new ArrayList<>();
            ExcelUtil.createExcelField(PROPERTIES, "recordNo", "中奖编号");
            ExcelUtil.createExcelField(PROPERTIES, "activityName", "活动名称");
            ExcelUtil.createExcelField(PROPERTIES, "phoneNum", "用户账号");
            ExcelUtil.createExcelField(PROPERTIES, "createDate", "参与时间");
            ExcelUtil.createExcelField(PROPERTIES, "prizeName", "奖品名称");
            ExcelUtil.createExcelField(PROPERTIES, "couponCodeMessage", "中奖劵码");
            if (prizeType == null || prizeType == 0) {
                ExcelUtil.createExcelField(PROPERTIES, "prizeType", "奖品类型");
            } else {
                ExcelUtil.createExcelField(PROPERTIES, "address", "用户地址");
            }
            ExcelUtil.createExcelField(PROPERTIES, "consumeScore", "消耗积分");
            ExcelUtil.downloadExcel(response, fileName, list, PROPERTIES);
        } catch (Exception e) {
            log.error("导出中奖记录条数异常=>{}", e.getMessage());
        }
    }

    @GetMapping("/export-by-signMessage")
    public void exportBySignMessage(HttpServletResponse response) {
        String fileName = "签约用户中奖记录";
        try {
            List<SignMessageParams> list;
            list = dataStatisticsService.exportBySignMessage();
            log.info("导出融创签约中奖记录条数=>{}", list.size());
            List<Map<String, String>> PROPERTIES = new ArrayList<>();
            ExcelUtil.createExcelField(PROPERTIES, "activityId", "活动ID");
            ExcelUtil.createExcelField(PROPERTIES, "activityName", "活动名称");
            ExcelUtil.createExcelField(PROPERTIES, "phoneNum", "用户账号");
            ExcelUtil.createExcelField(PROPERTIES, "createTime", "参与时间");
            ExcelUtil.createExcelField(PROPERTIES, "prizeName", "奖品名称");
            ExcelUtil.createExcelField(PROPERTIES, "projectName", "房产信息");
            ExcelUtil.downloadExcel(response, fileName, list, PROPERTIES);
        } catch (Exception e) {
            log.error("导出中奖记录条数异常=>{}", e.getMessage());
        }
    }

    //////////////////////////////////////////// 下面是总数据和详情数据有关

    /**
     * 获取活动营销平台pvuv等相关数据
     */
    @GetMapping("/get-data")
    public ResultInfo getData(@RequestParam(value = "pageNum", defaultValue = "0") int pageNum,
                              @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                              @RequestParam(value = "activityId", required = false) Integer activityId) {
        String user = getPrincipal().getUsername();
        String authoritiesStr = getPrincipal().getAuthoritiesStr();
        List<ActivityRoleUser> byUsername = activityRoleUserRepository.findByUsername(user);
        if (byUsername.get(0).getLookData() == 0) {
            return new ResultInfo("ERROR", "您没有查询数据的权限", null);
        }
        try {
            Page<Datas> pageList;
            if (!authoritiesStr.equals("ROLE_USER_SELF")) {
                user = null;
            }
            pageList = dataStatisticsService.findAllDataList(pageNum, pageSize, activityId, user);
            return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), String.valueOf(pageList.getTotalElements()), pageList.getContent());
        } catch (Exception e) {
            log.error("查询pvuv等数据异常=>{}", e.getMessage());
            return new ResultInfo("ERROR", "查询数据异常", null);
        }
    }

    /**
     * 获取活动详情数据
     *
     * @param activityId 活动id
     */
    @GetMapping("/find-day-data")
    public ResultInfo findDayData(@RequestParam("activityId") String activityId,
                                  @RequestParam(value = "pageNum", defaultValue = "0") int pageNum,
                                  @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        return dataStatisticsService.findDayData(activityId.trim(), pageNum, pageSize);
    }

    /**
     * 导出活动日数据详情
     */
    @GetMapping("/export-day-data")
    public void exportDayData(@RequestParam("activityId") String activityId, HttpServletResponse response) {
        String fileName = "活动详情数据";
        try {
            List<LogCountParams> list = dataStatisticsService.exportDayData(activityId);
            log.info("导出查询活动日详情数据条数=>{}", list.size());
            List<Map<String, String>> PROPERTIES = new ArrayList<>();
            ExcelUtil.createExcelField(PROPERTIES, "activityName", "活动名称");
            ExcelUtil.createExcelField(PROPERTIES, "day", "日期");
            ExcelUtil.createExcelField(PROPERTIES, "pv", "页面点击次数(pv)");
            ExcelUtil.createExcelField(PROPERTIES, "uv", "页面点击人数(uv)");
            ExcelUtil.createExcelField(PROPERTIES, "totalTimes", "活动参与总次数");
            ExcelUtil.createExcelField(PROPERTIES, "totalPeople", "活动参与总人数");
            ExcelUtil.createExcelField(PROPERTIES, "consumeScore", "消耗积分值");
            ExcelUtil.createExcelField(PROPERTIES, "countBill", "奖励积分下发数");
            ExcelUtil.downloadExcel(response, fileName, list, PROPERTIES);
        } catch (Exception e) {
            log.error("导出活动日详情数据异常=>{}", e.getMessage());
        }
    }

    /**
     * 实物点击发货
     */
    @PostMapping("/updateEntityStrategy")
    public ResultInfo updateEntityStrategy(@RequestBody @Valid List<String> recordIdList) {
        return dataStatisticsService.updateEntityStrategy(recordIdList);
    }
}
